//
//  TableViewController.m
//  Tomosoft
//
//  Created by WE on 15-2-5.
//  Copyright (c) 2015年 itcast. All rights reserved.
//

#import "LatterViewController.h"
#import "LatterInfoViewController.h"
#import "MemberLetterDto.h"
#import "LatterCell.h"


@interface LatterViewController ()<UIAlertViewDelegate>


@end

@implementation LatterViewController
{
    AFHTTPRequestOperationManager *_manager;
    UIBarButtonItem *_doneItem;
    UIImage * _image;
    UIBarButtonItem * _back;
    UIBarButtonItem * _delete;
}

- (void)viewDidLoad
{
 //   self.tableView.idsDic = [[NSMutableDictionary alloc] init];
    self.tableView.idsArray = [[NSMutableArray alloc] init];
    _image = [[UIImage imageNamed:@"ico_back_40.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    _back = [[UIBarButtonItem alloc]initWithImage:_image style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    _doneItem = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(modifyButton)];
    _delete = [[UIBarButtonItem alloc] initWithTitle:@"删除" style:UIBarButtonItemStylePlain target:self action:@selector(deleteButton)];
//    [_delete setTintColor:[UIColor colorWithWhite:0.9 alpha:1]];
    _delete.enabled = NO;
    [_doneItem setTintColor:WhiteColor];
    self.navigationItem.rightBarButtonItem = _doneItem;
    self.navigationItem.title=@"消息中心";
    _tableView.refreshFooterButton.hidden=NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.tableView registerClass:[LatterCell class] forCellReuseIdentifier:@"LatterCell"];
    [self.tableView setSeparatorInset:(UIEdgeInsetsMake(0,0, 0, 0))];
    self.tableView.rowHeight=60;
    [self.tableView setRefreshHeader:YES];
    [super viewDidLoad];
    __block LatterViewController *controller = self;
    self.tableView.upBlock=^(void){
        [controller.tableView initLastData];
    };
    self.tableView.pullBlock=^(void){
         [controller.tableView initData];

    };
}

- (void)deleteButton{
    
    [[[UIAlertView alloc]initWithTitle:@"请注意"
                              message:@"是否确认删除消息？"
                             delegate:self
                    cancelButtonTitle:nil
                    otherButtonTitles:@"删除",@"取消", nil] show];

}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
            
        NSMutableString * str=[[NSMutableString alloc]init];
        [str appendString:@"["];
        for (int i=0; i<self.tableView.idsArray.count; i++) {
            MemberLetterDto *m =self.tableView.idsArray[i];
            [str appendString:[NSString stringWithFormat:@"{\"letterId\":\"%@\",\"memberLetterId\":\"%@\",\"letterType\":\"%d\",\"status\":3},",m.LetterId,m.MemberLetterId,m.LetterType]];
        }
        [str deleteCharactersInRange:NSMakeRange(str.length-1,1)];
        [str appendString:@"]"];
        NSString *url = [NSString stringWithFormat:@"%@Letter/UpdateLetter",BaseURL];
        NSURL *URL=[NSURL URLWithString:url];//不需要传递参数
        NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];//默认为get请求
        request.timeoutInterval=30.0;//设置请求超时为5秒
        request.HTTPMethod=@"POST";//设置请求方法
        [request addValue:[Util valueOfPlistKey:@"URL_VERSION" fileName:@"url"] forHTTPHeaderField:@"version"];
//        [[[UIAlertView alloc]initWithTitle:@""
//                                   message:str
//                                  delegate:self
//                         cancelButtonTitle:nil
//                         otherButtonTitles:@"删除",@"取消", nil] show];

        //设置请求体
        NSString *param=[NSString stringWithFormat:@"memberid=%@&jsonLetterList=%@&signature=%@",Getmemberid,str,[Util getSignature:[NSString stringWithFormat:@"%@%@",Getmemberid,str]]];
        param = [param stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"];

        //把拼接后的字符串转换为data，设置请求体
        request.HTTPBody=[param dataUsingEncoding:NSUTF8StringEncoding];
        NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
        NSError *err;
        NSMutableDictionary * dic =[NSJSONSerialization JSONObjectWithData:received options:NSJSONReadingMutableContainers error:&err];
        NSNumber *data = [dic valueForKey:@"isSuccess"];
        if ([data isEqualToNumber:[[NSNumber alloc] initWithInt:1]]) {
            [_doneItem setTitle:@"编辑"];
            [self.tableView.idsArray removeAllObjects];
            [self.tableView setEditing:NO animated:YES];
            self.navigationItem.leftBarButtonItem = _back;
            [self.tableView initData];
            
        } else{
            [[[UIAlertView alloc] initWithTitle: @"删除失败" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
            
        }
    }
}
- (void)modifyButton
{
    if (self.tableView.editing) {
        [_doneItem setTitle:@"编辑"];
        [self.tableView.idsArray removeAllObjects];
        [self.tableView setEditing:NO animated:YES];
         self.navigationItem.leftBarButtonItem = _back;
        
    }else{
        [_doneItem setTitle:@"取消"];
        [self.tableView setEditing:YES animated:YES];
        self.navigationItem.leftBarButtonItem = _delete;
        [_delete setTintColor:[UIColor colorWithWhite:0.9 alpha:1]];
        _delete.enabled = NO;

    }
    
}
- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (id)init{
    self = [super init];
    if (self) {
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated{
 [self.tableView initData];
   [ super viewWillAppear:animated];
}
@end
